from typing import Annotated, Generator

from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.orm import Session

from app.core.config import settings
from app.core.exceptions import AuthenticationError
from app.crud import member_service as user_crud
from app.db.session import SessionLocal
from app.models.member import MemberDo
from app.schemas.member import MemberVo

# OAuth2密码流配置（获取令牌的登录接口路径）
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/sms/send")


# 数据库会话依赖（保持不变）
def get_db() -> Generator:
    db: Session = SessionLocal()
    try:
        yield db
    finally:
        db.close()


DbDependency = Annotated[Session, Depends(get_db)]
TokenDependency = Annotated[str, Depends(oauth2_scheme)]


# 获取当前登录用户（仅校验登录状态，不校验管理员权限）
def get_current_user(
        db: DbDependency,
        token: TokenDependency
) -> MemberVo:
    try:
        # 解码JWT令牌
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
        )
        user_id: str = payload.get("sub")
        if user_id is None:
            raise AuthenticationError(message="无法验证凭据：用户ID不存在")
    except JWTError:
        raise AuthenticationError(message="无法验证凭据：令牌无效或已过期")

    # 查询用户信息
    user: MemberDo = user_crud.get_member_by_id(db, user_id=int(user_id))
    if not user:
        raise AuthenticationError(message="用户不存在或已被删除")
    # 直接返回用户对象
    return MemberVo.model_validate(user)


# 当前登录用户的依赖（供接口直接使用）
CurrentUserDependency = Annotated[MemberVo, Depends(get_current_user)]
